﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MallInteractiveMap.CustomControl
{
    public class FileUploadTypeValidator : CustomValidator
    {
        public FileUploadTypeValidator()
        {
            //base.ValidationExpression = @"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.pdf)$";
            base.ErrorMessage = "gif, jpg and jpeg files are allowed.";
            base.Text = "*";
            base.SetFocusOnError = true;
            base.ToolTip = "gif, jpg and jpeg files are allowed.";
            base.ClientValidationFunction = "ClientValidateFileType";
            this.FileTypes = "gif|GIF|jpg|JPG|jpeg|JPEG";
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), this.ClientID + "ADDScript", GetScript(), true);
        }

        protected override bool OnServerValidate(string value)
        {
            //return base.OnServerValidate(value);
            FileUpload fu = this.Parent.FindControl(this.ControlToValidate) as FileUpload;
            if (fu != null && !string.IsNullOrEmpty(fu.FileName))
            {
                string ext = System.IO.Path.GetExtension(fu.FileName);
                string[] fileTypes = this.FileTypes.Split('|');
                foreach (string item in fileTypes)
                {
                    if (!ext.Equals("." + item))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public string FileTypes { get; set; }

        private string GetScript()
        {
            string script = string.Empty;
            script = @"function ClientValidateFileType(source, arguments) {"
            + " var FilePath = arguments.Value;"
            + " var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();"
            + " var exten = new Array();"
            + " exten = \"" + this.FileTypes + "\";"
            + " var  extens = exten.split(\"|\");"
            + " var isValid = false;"
            + " for (var i = 0; i < extens.length; i++) {"
            + "     if (extens[i] == Extension) {"
            + "         isValid = true;"
            + "         break;"
            + "     }"
            + " }"
            + " arguments.IsValid = isValid;"
        + " }";
            return script;
        }
    }
}
